﻿using BrnMall.Manager.Domain.WeChat;
using BrnMall.Manager.Manager.WeChat;
using BrnMall.WeiXin.Sdk;
using BrnMall.WeiXin.Sdk.Domain;
using BrnMall.WeiXin.Sdk.Work;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BrnMall.Services.WJK
{
    /// <summary>
    /// 企业微信业务处理
    /// </summary>
    public class WorkWeChats
    {
        /// <summary>
        /// 获取企业的AccessToken
        /// </summary>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public static PermanentCodeInfo GetAccessToken(int storeId)
        {
            //永久授权码
            var permanentCode = PermanentCodeManager.GetByStoreId(storeId, "ai销售");

            //不能超过2小时
            if (string.IsNullOrEmpty(permanentCode.access_token) ||
                (DateTime.Now.Subtract(permanentCode.last_expires).TotalMinutes > 100))
            {
                //获取ticket
                var ticket = SuiteTicketManager.GetSuiteTicket(1);

                Suite_Token suiteToken = AIHelper.Get_Suite_Token(ticket.SuiteTicket);

                //重新获取企业access_token
                AccessToken token = AIHelper.get_corp_token(suiteToken, permanentCode.permanent_code, permanentCode.corpid);

                //保存access_token
                PermanentCodeManager.UpdateAccessToken(permanentCode.Id, token.Access_Token, DateTime.Now);

                permanentCode = PermanentCodeManager.GetByStoreId(storeId, "ai销售");
            }

            return permanentCode;
        }
    }
}